import React, { useState, useCallback } from 'react';

import styles from './use_state_form.css';

function useFormItem(initValue: any, convert?: Function) {
  const [value, setValue] = useState(initValue);
  const handleChange = useCallback((evt: React.ChangeEvent) => {
    const { value } = evt.target as HTMLInputElement;
    if (convert) {
      setValue(convert(value));
    } else {
      setValue(value);
    }
  }, []);
  return {
    value: value,
    onChange: handleChange,
  };
}

function useFormItemChecked(initValue: any, convert?: Function) {
  const [value, setValue] = useState(initValue);
  const handleChange = useCallback((evt: React.ChangeEvent) => {
    const { checked } = evt.target as HTMLInputElement;
    setValue(checked);
  }, []);
  return {
    value: value,
    onChange: handleChange,
  };
}

export default function() {
  const username = useFormItem('李勇');
  const score = useFormItem(100, Number);
  const passed = useFormItemChecked(true, Boolean);
  console.log(
    'form values',
    username.value,
    score.value,
    typeof score.value,
    passed.value,
  );
  return (
    <div className={styles.normal}>
      <h1>Page use_state_form</h1>
      <form>
        <input type="text" {...username} />
        <br />
        <input type="number" {...score} />
        <br />
        <div>
          <input type="checkbox" {...passed} />
        </div>
      </form>
      <div>
        filled values: {username.value} {score.value}{' '}
        {passed.value ? 'passed' : 'failed'}
      </div>
    </div>
  );
}
